package by.ostrovsky.webhousingsystem.dao.implementation;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;

import by.ostrovsky.webhousingsystem.dao.implementation.idao.IOperateDAO;
import by.ostrovsky.webhousingsystem.dao.implementation.idao.IReadDAO;
import by.ostrovsky.webhousingsystem.exception.CommonException;
import by.ostrovsky.webhousingsystem.exception.OperationErrorException;
import by.ostrovsky.webhousingsystem.hibernate.HibernateUtil;
import by.ostrovsky.webhousingsystem.hibernate.entity.TaskGroup;

public class MySQLTaskGroupDAO implements
		IOperateDAO<List<TaskGroup>, Boolean>, IReadDAO<TaskGroup>{
	private static Logger logger = Logger.getLogger(MySQLTaskGroupDAO.class);

	@Override
	public List<TaskGroup> readAll() throws CommonException {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			@SuppressWarnings("unchecked")
			List<TaskGroup> list = session.createCriteria(TaskGroup.class)
					.list();
			session.getTransaction().commit();
			session.close();

			return list;
		} catch (HibernateException e) {
			throw new OperationErrorException();
		}
	}

	@Override
	public Boolean update(List<TaskGroup> object) throws CommonException {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			for (TaskGroup tg : object) {
				try {
					session.update(tg);
				} catch (HibernateException ex) {
					logger.error(ex);
				}
			}
			session.getTransaction().commit();
			session.close();
			return true;
		} catch (HibernateException e) {
			logger.error(e);
			throw new OperationErrorException();
		}
	}

	@Override
	public Boolean create(List<TaskGroup> taskGroup) throws CommonException {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			for (TaskGroup tg : taskGroup) {
				try {
					session.save(tg);
				} catch (HibernateException ex) {
					logger.error(ex);
				}
			}
			session.getTransaction().commit();
			session.close();
			return true;
		} catch (HibernateException e) {
			logger.error(e);
			throw new OperationErrorException();
		}
	}

	@Override
	public Boolean delete(List<TaskGroup> list) throws CommonException {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			for (TaskGroup tg : list) {
				try {
					session.delete(tg);
				} catch (HibernateException ex) {
					logger.error(ex);
				}
			}
			session.getTransaction().commit();
			session.close();
			return true;
		} catch (HibernateException e) {
			logger.error(e);
			throw new OperationErrorException();
		}
	}

	@Override
	public TaskGroup read(TaskGroup object) throws CommonException {
		// TODO Auto-generated method stub
		return null;
	}
}
